from info import models
from info.modules.index import index_blue
from flask import current_app, render_template, session, jsonify, request, g  # flask中app的原生对象

from info.utils.commons import user_login_data
from info.utils.response_code import RET


# 首页展示
@index_blue.route('/', methods=['GET', 'POST'])
@user_login_data
def show_index():
    try:
        # user_id = session.get('user_id')
        # user = None
        # if user_id:
        #     user = models.User.query.get(user_id)

        # 获取新闻列表，根据点击量查询前十条新闻
        news = models.News.query.order_by(models.News.clicks.desc()).limit(10).all()
        news_list = []
        for item in news:
            news_list.append(item.to_dict())

        # 获取所有的分类数据
        categores = models.Category.query.all()
        category_list = []
        for item in categores:
            category_list.append(item.to_dict())
        data = {
            'user_info': g.user.to_dict() if g.user else "",
            'news': news_list,
            'category_list': category_list
        }
        return render_template('news/index.html', data=data)
    except Exception as e:
        print(e)
        return jsonify(errno=RET.UNKOWNERR, errmsg='位置错误')


# 网站标识
@index_blue.route('/favicon.ico')
def get_web_logo():
    return current_app.send_static_file('news/favicon.ico')


# 统一的返回404页面
@index_blue.route('/404')
@user_login_data
def page_not_found():
    data = {
        'user_info': g.user.to_dict() if g.user else ""
    }
    return render_template('news/404.html', data=data)


# 新闻列表展示
@index_blue.route('/newslist')
def newslist():
    try:
        # 1, 获取参数
        cid = request.args.get('cid', '1')
        page = request.args.get('page', '1')
        per_page = request.args.get('per_page', '10')
        # 2, 参数类型转换
        page = int(page)
        per_page = int(per_page)
        # 3, 分页查询
        # 判断分类id是否为1
        # 第一种方法
        """
        if cid == '1':
            paginate = models.News.query.order_by(
                models.News.create_time.desc()).paginate(page=page, per_page=per_page)
        else:
            paginate = models.News.query.filter(models.News.category_id == cid).order_by(
                models.News.create_time.desc()).paginate(page=page, per_page=per_page)
        """
        # 第二种方法
        """
        filters = ''
        if cid != '1':
            filters = (models.News.category_id == cid)
        paginate = models.News.query.filter(filters).order_by(
            models.News.create_time.desc()).paginate(page=page, per_page=per_page)
        """

        # 第三种方法
        filters = []
        if cid != '1':
            filters.append(models.News.category_id == cid)
        paginate = models.News.query.filter(*filters).order_by(
            models.News.create_time.desc()).paginate(page=page, per_page=per_page)

        # 4, 获取到分页对象中的属性，总页数，当前页，当前页的对象列表
        totalPage = paginate.total
        currentPage = paginate.page
        items = paginate.items
        # 5, 将对象列表转成字典列表
        news_list = []
        for news in items:
            news_list.append(news.to_dict())
    except Exception as e:
        print(e)
        current_app.logger.error(e)
        return jsonify(errno=RET.UNKOWNERR, errmsg="未知错误！")
    # 6, 携带数据，返回响应
    return jsonify(errno=RET.OK, errmsg='获取新闻列表成功！', totalPage=totalPage, currentPage=currentPage,
                   newsList=news_list)
